package com.nn.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nn.R;
import com.nn.entity.LoginUser;
import com.nn.entity.SysUser;
import com.nn.mapper.SysUserMapper;
import com.nn.service.AdminLoginService;
import com.nn.utils.JwtUtil;
import com.nn.utils.RedisCache;
import com.nn.utils.SecurityUtils;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author 年年
 * 后台用户登录
 */

@Service
public class AdminLoginServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements AdminLoginService {

    @Resource
    private AuthenticationManager authenticationManager;

    @Resource
    private RedisCache redisCache;

    @Override
    public R login(SysUser user) {
        UsernamePasswordAuthenticationToken token
                = new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(token);
        if (Objects.isNull(authenticate))
            throw new RuntimeException("用户名或密码错误！");
        //获取userid生成token
        LoginUser loginUser= (LoginUser) authenticate.getPrincipal();
        Long id = loginUser.getUser().getId();
        String jwt = JwtUtil.createJWT(id.toString());

        //将token存入redis
        redisCache.setCacheObject("login" +id,loginUser);
        //封装响应对象
        Map<String, String> map = new HashMap<>();
        map.put("token",jwt);
        return R.okResult(map);
    }

    @Override
    public R logout() {
        Long id = SecurityUtils.getUserId();
        redisCache.deleteObject("login:"+id);
        return R.okResult();
    }


}
